package com.wzzc.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DockerUtils {

	/**
	 * 得到Docker镜像IP
	 * @param name
	 * @return
	 */
	public static String getDockerIp(String name) {
		String line = null;
		String ip = null;
		try {
			Process p = Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c","docker inspect --format '{{ .NetworkSettings.IPAddress }}' " + name });
			InputStream is = p.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				ip = line;
			}
			p.waitFor();
			is.close();
			br.close();
			p.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}
	
	/**
	 * 打开Docker桌面
	 * @param name
	 */
	public static void openDocker(String name) {
		try {
			Process process = Runtime.getRuntime().exec("docker run -t -i -d --rm --name " + name + " zyc/ubuntu_addrunsh_xfce4:v2 /run.sh");
			InputStream is = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = null;
			System.out.println("Docker Open Log:");
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			process.waitFor();
			is.close();
			br.close();
			process.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭Docker镜像
	 * @param name
	 * @throws Exception 
	 */
	public static void closeDocker(String name) throws Exception {
		Process process = Runtime.getRuntime().exec("docker stop -t 0 "+name);
		InputStream is = process.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		System.out.println("Docker Close Log:");
		while ((line = br.readLine()) != null) {
			System.out.println("Docker Image "+line+" closed");
		}
		process.waitFor();
		is.close();
		br.close();
		process.destroy();
	}
	
	/**
	 * 关闭全部镜像
	 * @throws IOException 
	 */
	public static void closeAllDocker() throws Exception {
		Process process = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c","docker stop -t 0 $(docker ps -q)"});
		InputStream is = process.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		System.out.println("Docker Close Log:");
		while ((line = br.readLine()) != null) {
			System.out.println("Docker Image "+line+" closed");
		}
		process.waitFor();
		is.close();
		br.close();
		process.destroy();
	}
	
}
